<template>
  <el-dialog
      :title="isEdit ? '编辑医生' : '添加医生'"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="doctor-form"
    >
      <el-form-item label="姓名" prop="doctorName">
        <el-input v-model="form.doctorName" placeholder="请输入医生姓名"/>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号"/>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
            v-model="form.password"
            type="password"
            :placeholder="isEdit ? '不修改请留空' : '请输入密码'"
            show-password
        />
      </el-form-item>
      <el-form-item label="负责社区" prop="communityId">
        <el-select
            v-model="form.communityId"
            placeholder="选择社区"
            filterable
            remote
            :remote-method="filterCommunity"
            :loading="communityLoading"
            clearable
            style="width: 200px"
        >
          <el-option
              v-for="item in filteredCommunityList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:8080/File/upload"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.avatar" :src="form.avatar" class="avatar" alt=""/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, computed, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import type {Doctor, DoctorUpdateRequest, DoctorAddRequest} from '@/types/doctor'
import type {Community} from '@/types/community'
import {addDoctor, updateDoctor} from '@/api/doctor'
import {getAllCommunities} from '@/api/community'
import {useUserStore} from '@/stores/user'

const props = defineProps<{
  modelValue: boolean
  doctor?: Doctor
  isEdit: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const userStore = useUserStore()
const formRef = ref()
const loading = ref(false)

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const communityList = ref<Community[]>([])

// 获取社区列表
const fetchCommunityList = async () => {
  try {
    communityList.value = await getAllCommunities()
    communityList.value = [{id: 0, name: '无'}, ...communityList]
  } catch (error) {
    console.error('获取社区列表失败:', error)
  }
}

// 社区过滤方法
const filterCommunity = (query: string) => {
  if (query) {
    communityLoading.value = true
    setTimeout(() => {
      filteredCommunityList.value = communityList.value.filter(item => {
        return item.name.includes(query)
      })
      communityLoading.value = false
    }, 200)
  } else {
    filteredCommunityList.value = communityList.value
  }
}

const communityLoading = ref(false)
const filteredCommunityList = ref<Community[]>([])

// 在组件挂载时获取社区列表
fetchCommunityList()

const form = ref({
  id: undefined as number | undefined,
  doctorName: '',
  phone: '',
  password: '',
  avatar: '',
  communityId: undefined as number | undefined,
})

const rules = computed(() => ({
  doctorName: [
    {required: false, message: '请输入医生姓名', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  password: [
    {required: !props.isEdit, message: '请输入密码', trigger: 'blur'},
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,}$/,
      min: 6,
      max: 20,
      message: '请输入正确的密码（6位及以上字母+数字组合）',
      trigger: 'blur'
    }
  ],
  communityId: [
    {required: false, message: '请选择负责社区', trigger: 'change'}
  ]
}))

// 上传相关
const uploadHeaders = computed(() => ({
  Authorization: userStore.token
}))

// 监听 doctor 属性变化，更新表单数据
watch(
    () => props.doctor,
    (newVal) => {
      if (newVal) {
        form.value = {
          id: newVal.id,
          doctorName: newVal.doctorName,
          phone: newVal.phone,
          password: '',
          avatar: newVal.avatar,
          communityId: newVal.communityId
        }

        // 确保当前社区在过滤列表中
        if (newVal.communityId) {
          const selectedCommunity = communityList.value.find(
              c => c.id === newVal.communityId
          )
          if (selectedCommunity && !filteredCommunityList.value.some(c => c.id === selectedCommunity.id)) {
            filteredCommunityList.value = [selectedCommunity, ...filteredCommunityList.value]
          }
        }
      } else {
        form.value = {
          id: undefined,
          doctorName: '',
          phone: '',
          password: '',
          avatar: '',
          communityId: undefined
        }
      }
    },
    {immediate: true, deep: true}
)

watch(
    () => communityList.value,
    (newVal) => {
      filteredCommunityList.value = [{id: 0, name: '无'}, ...newVal]

      if (form.value.communityId) {
        const selectedCommunity = newVal.find(c => c.id === form.value.communityId)
        if (selectedCommunity && !filteredCommunityList.value.some(c => c.id === selectedCommunity.id)) {
          filteredCommunityList.value = [selectedCommunity, ...newVal]
        }
      }
    },
    {deep: true}
)

// 监听对话框显示状态，重置表单
watch(
    () => dialogVisible.value,
    (newVal) => {
      if (!newVal) {
        handleClose()
      } else if (props.doctor) {
        // 当对话框打开且有 doctor 数据时，更新表单
        form.value = {
          id: props.doctor.id,
          doctorName: props.doctor.doctorName,
          phone: props.doctor.phone,
          password: '', // 编辑时密码默认为空
          avatar: props.doctor.avatar,
          communityId: props.doctor.communityId
        }
      }
    }
)

// 头像上传前的验证
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 20

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 20MB!')
  }
  return isJPG && isLt2M
}

// 头像上传成功的回调
const handleAvatarSuccess = (response: any) => {
  if (response.code === 200) {
    form.value.avatar = response.data
    ElMessage.success('头像上传成功')
  }
}

// 头像上传失败的回调
const handleAvatarError = () => {
  ElMessage.error('头像上传失败，请重试')
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
  form.value = {
    id: undefined,
    doctorName: '',
    phone: '',
    password: '',
    avatar: '',
    communityId: undefined
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    if (props.isEdit) {
      // 编辑模式：如果密码为空，则使用原始密码
      const submitData: DoctorUpdateRequest = {
        id: form.value.id!,
        doctorName: form.value.doctorName,
        phone: form.value.phone,
        avatar: form.value.avatar,
        communityId: form.value.communityId,
        password: form.value.password || props.doctor?.password || ''
      }

      await updateDoctor(submitData)
      ElMessage.success('更新成功')
      emit('success')
      dialogVisible.value = false
    } else {
      // 添加模式：必须包含密码
      if (!form.value.password) {
        ElMessage.error('请设置密码')
        return
      }
      const submitData: DoctorAddRequest = {
        phone: form.value.phone,
        password: form.value.password,
        doctorName: form.value.doctorName,
        avatar: form.value.avatar,
        communityId: form.value.communityId
      }
      await addDoctor(submitData)
      ElMessage.success('添加成功')
      emit('success')
      dialogVisible.value = false
    }
  } catch (error) {
    console.error('表单提交失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.doctor-form {
  padding: 20px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  border-radius: 50%;
}
</style> 